import Vue from 'vue'
import Router from 'vue-router'
import {getToken} from "@/utils/token";
import store from '@/store'
Vue.use(Router)

// 后台公共组件
import Layout from '@/components/layout/Index.vue'

//菜单管理
import Menu from '@/views/menu/Menu'


const Auths = ()=>import('@/views/auths/Auths.vue')

// 用户中心
const Users = ()=>import('@/views/users/Users.vue')
const UsersSaveView = ()=>import('@/views/users/UsersSaveView.vue')
// 个人信息
const User = ()=>import('@/views/user/User')

// 角色管理
const Roles = ()=>import('@/views/roles/Roles.vue')
const RolesSaveView = ()=>import('@/views/roles/RolesSaveView.vue')

// 标签管理
const Labels = ()=>import('@/views/labels/Labels.vue')

// 文章类型
const ArticleTypes = ()=>import('@/views/articleType/ArticleTypes.vue')

// 文章提交
const SubmitArticle = ()=>import('@/views/article/SubmitArticle')

// 登录
const Login =  ()=>import('@/views/login/Login.vue')

// 重置密码
const PassWordNew = ()=>import('@/views/login/PassWordNew.vue')

// 注册
const Register = ()=>import('@/views/login/Register.vue')

// 公用组件编辑器
const WangEditor=  ()=>import('@/components/wangEditor/WangEditor.vue')

const NotFound = ()=>import('@/components/notFound/404.vue')


export const constantRouterMap  = [
    {
        path: '/home',
        name: 'home',
        component:()=>import('@/components/Home.vue'), // 这个是路由懒加载的方法
        meta: { title: '首页',menu_code: 'home' },
    },
    {
        path: '/',
        redirect: {name: "login"}
    },

    {
        path:'/login',
        name:'login',
        component:Login,
        meta:{
            title : '登录',
            show:true,//控制侧边栏是否显示
        }
    },
    {
        path: '/passWordNew',
        component:PassWordNew,
        meta:{
            title : '重置密码',
            show:true,//控制侧边栏是否显示

        }
    },
    {
        path: '/register',
        component:Register,
        meta:{
            title : '注册',
            show:true,//控制侧边栏是否显示

        }
    },

    {
        path:'/wangEditor',
        component:WangEditor,
        meta: {title: '编辑器'}
    },

    {
        path: '/menu',
        redirect: {name: 'menu'},
        component:Layout,
        meta: { title: '菜单管理',menu_code: 'MenuConfig' },
        children: [{
            path:'/menu/index',
            name:'menu',
            meta: { title: '菜单中心',menu_code: 'menu_system_menu' },
            component: Menu

        }],

    },
    {
        path: '/auths',
        redirect: {name: 'auths'},
        component:Layout,
        meta: { title: '权限管理',menu_code:'AuthNavigation' },
        children:[{
            path:'/auths/index',
            name:'auths',
            component:Auths,
            meta: { title: '权限中心',menu_code:'auth' },
        }]
    },

    {
        path:'/users',
        component:Layout,
        redirect: {name:'users'},
        meta: {title: '用户菜单',menu_code:'UserNavigation'},
        children: [{
            path:'/users/index',
            name:'users',
            component: Users,
            meta: { title: '用户中心',menu_code:'users' },

        }]
    },

    {
        path: '/user',
        redirect: {name: 'user'},
        component:Layout,
        meta: { title: '个人菜单',menu_code: 'UserInfo' },
        children: [{
            path: '/user/index',
            name: 'user',
            component:User,
            meta: { title : '个人信息',menu_code: 'user'},
        }]
    },
    {
        path: '/roles',
        redirect: {name: 'roles'},
        component:Layout,
        meta: { title: '角色管理',menu_code:'RoleNavigation' },
        children:[{
            path:'/roles/index',
            name:'roles',
            component:Roles,
            meta: { title: '角色中心',menu_code:'roles' },
        }]
    },

    {
        path: '/labels',
        redirect: {name: 'labels'},
        meta: { title: '标签管理' ,menu_code: 'LabelNavigation'},
        component:Layout,
        children: [{
            path:'/labels/index',
            name:'labels',
            meta: { title: '标签中心',menu_code: 'label' },
            component: Labels
        }],

    },
    {
        path: '/articleTypes',
        redirect: {name: 'articleTypes'},
        component:Layout,
        meta: { title: '文章类型管理',menu_code: 'articleTypeNavigation' },
        children:[{
            path:'/articleTypes/index',
            name:'articleTypes',
            meta: { title: '文章类型中心',menu_code:'articleType' },
            component:ArticleTypes
        }],

    },
    {

        path:'/article',
        name:'article',
        redirect: {name: 'submitArticle'},
        meta: { title: '文章管理' ,menu_code: 'ArticleNavigation'},
        component:Layout,//当父类路由不需要显示的时候可以这样先写
        children:[{
            path:'/article/submitArticle',
            name:'submitArticle',
            component:SubmitArticle,
            meta: { title: '文章提交',menu_code: 'article' },

        }]
    },
    {
        // 这里必须要在最后因为匹配的是所有
        path: '*',
        name:'NotFound',
        meta:{
            isLogin : true,  // 自定义一个属性，true需要登录权限
            title:"404",
            show:true,//控制侧边栏是否显示
        },
        component:NotFound,
    },
];
export const asyncRouterMap = [];

const router = new Router({
    mode: 'history', // 默认是hash模式
    routes: constantRouterMap
})

let loopCounter = 0;
const maxLoopCount = 3;

// router.beforeEach((to, from, next) => {
//     const hasToken = getToken("token");
//     console.log('to',to);
//     console.log('from',from);
//     if (loopCounter >= maxLoopCount) {
//         alert('已经进入死循环了');
//         console.error("已经进入死循环了.");
//         return;
//     }
//
//     if (hasToken && to.path === "/login") {
//         loopCounter++;
//         return next({ path: "/home" });
//     }
//
//     if (!hasToken && to.path !== "/login") {
//         loopCounter++;
//         return next({ path: "/login" });
//     }
//
//     if (to.name === "NotFound") {
//         return next();
//     }
//
//     if (hasToken) {
//         store
//             .dispatch("menus/menuAll")
//             .then(() => {
//                 const allMenus = store.state.menus.allMenus;
//
//                 if (allMenus.length === 0) {
//                     return next({ path: "/home" });
//                 }
//
//                 if (checkPermission(to, allMenus)) {
//                     return next();
//                 }
//
//                 return next({ path: '/404', });
//             })
//             .catch((error) => {
//                 console.error("Error fetching menus:", error);
//                 return next({ path: "/login" });
//             });
//     } else {
//         return next();
//     }
// });


function checkPermission(to, allMenus) {
    if (isPathInRoutes(to.path, allMenus)) {
        return true;
    }
    return false;
}


function isPathInRoutes(path, routes, level = 0) {
    if (level > 3) {
        return false;
    }

    return routes.some((route) => {
        if (route.path === path) {
            return true;
        }
        if (route.children) {
            return isPathInRoutes(path, route.children, level + 1);
        }
        return false;
    });
}

export default router